import router from '@/router'
import store from '@/store'
import { errorRoutes } from '@/framework/router'
import { getToken, setToken } from '@/framework/utils/auth'
import { loginWithToken } from '@/framework/api/user'
// 初始化路由
export async function dealRouter(toPath, roles) {
  store.dispatch('tagsView/delAllViews')
  // const accessRoutes = await store.dispatch('permission/generateRoutes', { roles: roles || store.getters.roles, appCode: (toPath === '/' ? '' : store.state.settings.appCode), path: toPath })

  const accessRoutes = await store.dispatch('permission/generateRoutes', { roles: roles || store.getters.roles, currentPath: toPath === '/' ? '' : toPath })
  router.addRoutes([...accessRoutes, ...errorRoutes]) // 拼接errorroutes
  // 从当前路由地址初始化当前的菜单
  if (store.getters.app_routes.length > 0) {
    initCurrentRoute(toPath, store.getters.app_routes)
  }
}
export const initCurrentRoute = function (toPath, routes) {
  for (const route of routes) {
    const { path, children, menuType } = route
    if (includePath(toPath, children)) {
      store.dispatch('permission/setCurrentRoutes', children)
      if (path.indexOf('/selfLayout') > -1 || menuType === 'layout') { // 2.3版本 无应用概念  当第一个菜单类型为菜单时   及menuType=='layout'    当前应用path为 `${path + index}`
        // store.dispatch('permission/setCurrentAppPath', `${path + index}`)
        store.dispatch('permission/setCurrentAppPath', toPath)
      } else {
        store.dispatch('permission/setCurrentAppPath', path)
      }
      return
    }
  }
  store.dispatch('permission/setCurrentRoutes', routes[0].children)
  store.dispatch('permission/setCurrentAppPath', routes[0].path)
}
export const includePath = function (path, routes) {
  let hasPath = false
  if (routes && routes.length > 0) {
    for (const route of routes) {
      if (route.path === path) {
        hasPath = true
        break
      } else {
        hasPath = includePath(path, route.children)
        if (hasPath) break
      }
    }
  }

  return hasPath
}
/**
 * @description: 处理单点登录逻辑
 * @param {*} to
 * @param {*} form
 * @param {*} next
 * @return {*}
 */
export const dealSingleSignOn = async function (to, form, next) {
  if (process.env.VUE_APP_SINGLE_SIGN_ON === '1') { // 如果单点登录
    if (to.path === '/login' && to.query.token) {
      //  集成到统一登录
      // 有则保存token至本地，请求getCurrentLoginUserInfo接口获取用户信息之后跳转至首页
      store.commit('user/SET_TOKEN', to.query.token)
      setToken(to.query.token)
      const { roles } = await store.dispatch('user/getInfo')
      const accessRoutes = await store.dispatch('permission/generateRoutes', roles)
      router.addRoutes(accessRoutes)
      if (store.getters.app_routes.length > 0) {
        initCurrentRoute(to.path, store.getters.app_routes)
      }
      store.dispatch('settings/getCurrentThemeInfo')
      next('/')
    } else if (to.path === '/login' && !to.query.token) {
      // 没有的话看看有没有页面加载即请求的接口，没有这种接口的话也请求getCurrentLoginUserInfo接口，会自动跳转至平台登录之后回跳回来拼接url里的token参数
      // await store.dispatch('user/getInfo')
      // 更换：（2）直接路由至后端接口地址（要求：可经过单点登录拦截器跳转逻辑），如（后端地址+/homePage/getHomeCompanyInfo）
      window.location.href = `${process.env.VUE_APP_BASE_API}/homePage/getHomeCompanyInfo`
      // next()
    } else {
      next()
    }
  } else {
    next()
  }
}
export const dealssoLogin = async function (to, form, next) {
  const loginparmas = {
    token: getToken(),
    ssoLoginParam: {
      ssoLoginFlag: true,
      authMode: to.query.authMode,
      state: to.query.state,
      appRedirectUrl: to.query.appRedirectUrl
    },
    loginRequest: {
      tenantId: to.query.tenantId
    }
  }
  loginWithToken(loginparmas).then((res) => {
    if (res.success === true && res.data.appRedirectflag == true) {
      window.location.href = res.data.appRedirectUrl
    }
  })
}
